package com.sky.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDto;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    public EmployeeMapper employeeMapper;

    @Autowired
    public JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    //登录
    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO loginDTO) {
        // 根据用户名密码查询数据库 查询用户是否存在
        // Employee employee = empMapper.selectByUsernameAndPassword(loginDTO);
        Employee employee = employeeMapper.selectByUsername(loginDTO.getUsername());

        // 判断用户是否存在
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 浏览器传入的密码是明文 123456 数据库内的密码是密文的 employee.getPassword()是密文的
        // 转换成密文赋值给pssword
        String password = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());

        // 密码对不对
        if (!password.equals(employee.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        // 判断登录状态
        if (StatusConstant.DISABLE.equals(employee.getStatus())) {
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        // jwt内封装的内容
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        claims.put(JwtClaimsConstant.NAME, employee.getName());
        claims.put(JwtClaimsConstant.USERNAME, employee.getUsername());
        // 生成token令牌
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);

        //  把token保存到redis，并且给这个值设置一个过期时间 1小时
        redisTemplate.opsForValue().set("admin_token:" + token, employee.getId(),1, TimeUnit.HOURS);

        // 封装返回对象
        EmployeeLoginVO loginVO = new EmployeeLoginVO();

        loginVO.setId(employee.getId());
        loginVO.setUserName(employee.getUsername());
        loginVO.setName(employee.getName());
        loginVO.setToken(token);

        return loginVO;

    }

    //分页
    @Override
    public PageResult page(Integer page, Integer pageSize, String name) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        if (StringUtils.hasText(name)) {
            name = "%" + name + "%";
        }
        // 执行分页查询
        List<Employee> empList = employeeMapper.list(name);
        // 获取分页结果
        Page<Employee> p = (Page<Employee>) empList;
        //封装PageBean
        PageResult pageResult = new PageResult(p.getTotal(), p.getResult());

        return pageResult;
    }


    //修改员工
    @Override
    public void updatePass(EmployeeDto employeeDto) {

        employeeMapper.updatePass(employeeDto);
    }

    //添加员工
    @Override
    public void save(Employee employee) {

        employeeMapper.save(employee);
    }

    @Override
    public Employee selecById(Long id) {
        return employeeMapper.selectById(id);
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.update(employee);
    }

    //修改员工信息
    @Override
    public Integer updateEmp(Employee employee) {
        Integer it = employeeMapper.updateEmp(employee);
        return it;
    }

}
